import config from '@/config/es'
import { encode, decode } from 'crypto-js'

const install = (app) => {
	// 3. 注入组件选项
	app.config.globalProperties.$es = uni.$es = {
		// 初始化
		send (path = '', method = 'POST', body = {}) {
			// 此为自定义配置参数，具体参数见上方说明
			return uni.request({
				method: method,
				url: config.host + path,
				header: {
					authorization: 'Basic ' + encode(`${config.user}:${config.pass}`)
				},
				data: body
			})
		},
		// 搜索
		search (index, matchs = [], page = 1, size = 12) {
			const bool = {}
			matchs.map(([field, value, match]) => {
				if (['match_phrase', 'match'].includes(match)) {
					bool.must = {[match]: {}}
					bool.must[match][field] = value
				} else if(['prefix', 'term'].includes(match)) {
					(!bool.filter) && (bool.filter = [])
					bool.filter.push({[match]: {[field]: value}})
				} else {
					(!bool.filter || !bool.filter.term) && (bool.filter = [])
					bool.filter.push({[match]: {[field]: value}})
				}
			})
			return this.send(index + '/_search', 'POST', {
				size: size,  // 分页大小
				from: size * (page - 1),
				query: matchs.length == 0 ? {match_all: {}} : {bool: bool}	
			}).then(({data: {hits}, statusCode}) => {
				if(statusCode===200){
					return new Promise((resolve, reject) => {
					  resolve({list:hits.hits.map(r=>r._source), total:hits.total.value})
					})
				} else {
					return new Promise((resolve, reject) => {
					  reject()
					})
				}
			})
		},
		// get 获取一条记录
		get (index, id) {
			// callback API
			return this.send(index + '/_doc/' + id, 'GET')
		},
		// get 获取一条记录
		update (index, id, body = {}) {
			// callback API
			return this.send(index + '/_update/' + id, 'POST', [])
		},
		/*
		 *  删除文档
		 */
		del (index, id)
		{
				return this.send(index + '/_doc/' + id, 'DELETE')
		},
		/*
		 * 批量索引文档
		 */
		bulk (index, data = [], pk = 'id'){
			let body = [];
			max = data.length % 5000 - 1;
			for(const k in data) {
				body.push({
					'index': {
						_index: index,
						_id: data[k][pk]
					}
				})

				body.push(data[k])
				// Every 1000 documents stop and send the bulk request
				if (k > 0 && (k === max || k % 5000 === 0)) {             
						const responses = this.send(index + '/_bulk', 'POST', {body: body});
						body = []
				}
			}
		}
	}
}
export default {
	install
}